<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>颜色单位互转</title>
  <meta charset="utf-8">
</head>
<body>

<label>RGB：<input type="text" class="num"></label>
<button class="button"> 转 换</button>
<label>十六进制：<input type="text" class="result"></label>

<script type="text/javascript">
  var oRgb = document.querySelector(".num"),
    oHex = document.querySelector(".result"),
    oBtn = document.querySelector("button");
  //如果rgb框发生改变时自动清除16进制数据
  oRgb.oninput = function () {
    if (oHex.value !== "") {
      oHex.value = "";
    }
  };
  //如果16进制发生改变时自动清除rgb框数据
  oHex.oninput = function () {
    if (oRgb.value !== "") {
      oRgb.value = "";
    }
  };
  //给转换标签添加绑定事件
  oBtn.onclick = function () {
    var sVal, reg;
    //先判断哪边值时空,oNum不为空的转rgb框的数据
    if (oRgb.value) {
      sVal = oRgb.value;
      reg = /^rgb\(([01]?\d{1,2}|2[0-4]\d|25[0-5])(,([01]?\d{1,2}|2[0-4]\d|25[0-5])){2}\)$/i;
      if (reg.test(sVal)) {
        oHex.value = rgbToHex(sVal);

      } else {
        alert("不合法，请重新输入");
      }
    } else {     //若rgb框时空则
      sVal = oHex.value;
      reg = /^#([0-9A-Fa-f]{3}){1,2}$/i;
      if (reg.test(sVal)) {
        oRgb.value = hexToRGB(sVal);
      } else {
        alert("不合法，请重新输入");
      }
    }
  };

  //rgb转16进制
  function rgbToHex(val) {
    //创建一个正则，验证是不是数字
    var reg = /\d+/g;
    //创建一个变量aHex保存验证后的数值数组，
    var aHex = val.match(reg), sHex = "#";
    for (var i = 0; i < 3; i++) {
      sHex += ("0" + Number(aHex[i]).toString(16)).slice(-2);
    }
    return sHex;
  }

  function hexToRGB(val) {
    var reg, aRGB, sRGB = "rgb(";
    if (val.length === 4) {
      reg = /#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])/;
      val = val.replace(reg, "#$1$1$2$2$3$3");
    }
    reg = /\w{2}/g;
    aRGB = val.match(reg);
    for (var i = 0; i < 3; i++) {
      sRGB += parseInt(aRGB[i], 16) + ",";
    }
    sRGB = sRGB.slice(0, sRGB.length - 1) + ")";
    return sRGB;
  }
</script>
</body>
</html>